// pages/cart/index.js
import { getSetting, chooseAddress, openSetting, showModal, showToast } from "../../utils/asyncWX.js";
import regeneratorRuntime from "../../lib/runtime/runtime";

Page({
  data: {
    address: {},
    cart: [],
    allChecked: false,
    totalPrice: 0,
    totalNum: 0
  },
  onShow() {
    const address = wx.getStorageSync('address')
    const cart = wx.getStorageSync('cart')||[];
    
    this.setData({ address })
    this.setCart(cart)
  },
 
  // 添加收货地址
  async handleChooseAddress() {
    /* 
        用户对小程序授予的收货地址授权(确定，取消，未授权)
      <==> authSetting scope.address(true,false,undefined)
        1、3种情况可以直接调用获取收货地址，若用户取消，则诱导用户打开授权设置，获取权限
     */
    // 解决回调地狱
    try {
      const res1 = await getSetting()
      const scopeAddress = res1.authSetting['scope.address']
      if(scopeAddress===false) { 
        await openSetting()
      }
      let address = await chooseAddress()
      address.all = address.provinceName+address.cityName+address.countyName+address.detailInfo
      wx.setStorageSync('address', address);
    } catch (error) {
      console.log(error)
    } 
  },
  // 商品选中
  handleItemChange(e) {
    const goodsId = e.currentTarget.dataset.id
    let { cart } = this.data
    let index = cart.findIndex(v => v.goods_id===goodsId)
    cart[index].checked = !cart[index].checked
    this.setCart(cart)
  },
  // 设置购物车状态 重新计算工具栏
  setCart(cart) {
    let allChecked = true
    let totalPrice = 0
    let totalNum = 0
    cart.forEach(v => {
      if(v.checked) {
        totalPrice += v.num*v.goods_price
        totalNum += v.num
      }else {
        allChecked = false
      }
    })
    allChecked = cart.length!=0 ? allChecked : false
    this.setData({ 
      cart,
      totalPrice,
      totalNum,
      allChecked
    })
    wx.setStorageSync('cart', cart)
  },
  // 商品全选功能
  handleItemAllCheck() {
    let { cart, allChecked } = this.data
    allChecked=!allChecked
    cart.forEach(v => v.checked = allChecked)
    this.setCart(cart)
  },
  // 商品数量编辑
  async handleItemNumEdit(e) {      
    const { operation, id } = e.currentTarget.dataset
    let { cart } = this.data
    const index = cart.findIndex(v => v.goods_id===id)

    if(cart[index].num===1 && operation===-1) {
      const result = await showModal({ content: '是否删除商品？' })
      if (result.confirm) {
        cart.splice(index, 1)
        this.setCart(cart)
      }
    }else {
      cart[index].num += operation
      this.setCart(cart)
    }
  },
  // 结算功能 
  async handlePay() {
    const { address, totalNum } = this.data
    if(!address.userName) {
      await showToast({ title: '您没有选择收货地址' })
      return
    }
    if(totalNum===0) {
      await showToast({ title: '您没有选购商品' })
      return
    }
    // 跳转到支付界面
    wx.navigateTo({
      url: '/pages/pay/index'
    })
      
  }

})